import ProTable from '@ant-design/pro-table';
import { Form } from '@ant-design/compatible';
import React, { useState, useRef, useEffect, useCallback } from 'react';
import { Button,  message, Modal, Table, Row, Input } from 'antd';
import '@ant-design/compatible/assets/index.css';

import CreateForm from './components/CreateForm';
import { getDataTable, changeStatus, updateData } from './service.js';
import styles from './index.less';
import AuthComponent from '@/components/Authorized/AuthComponent';


const { confirm } =Modal

const DataDictionary = () => {
  const [createModalVisible, handleCreateModalVisible] = useState(false); // 新建弹框

  const [selectedRowKeys, handleSelectedRowKeys] = useState([]) // 勾选索引
  const [selectedRows, handleSelectedRows] = useState([]) // 勾选列
  const [dataSource, handleDataSource] = useState([]) // 列表数据
  const [keySearch, handleKeySearch] = useState('') // 搜索值
  const actionRef = useRef();

  
  const [inited, setInited] = useState(false) // 初始化
  const height = document.body.clientHeight - 366.5; // 表格高度自适应

  const columns = [
    {
      title: '类型',
      dataIndex: 'type',
    },
    {
      title: '字典键名',
      dataIndex: 'key',
      hideInSearch: true
    },
    {
      title: '字典键值',
      dataIndex: 'value',
      hideInSearch: true
    },
    {
      title: '描述',
      dataIndex: 'remark',
      hideInSearch: true
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInSearch: true,
      filters: false,
      valueEnum: {
        0: {
          text: '启用',
          status: 'Success',
        },
        1: '停用'
      }
    }
  ];
  useEffect(()=>{
    if (actionRef.current && inited) {
      actionRef.current.reload();
    } else {
      setInited(true)
    }
  },[keySearch])

  // 添加搜索值
  const beforeSearchSubmit = useCallback((params) => {
    let keySearch = params.type
    handleKeySearch(keySearch)
  },[])

  // 新建
  const handleSubmit = async (fields, text) => {
    const hide = message.loading(`正在${text}`);
    try {
      let res = await updateData(
        {...fields}
      );
      if (res.code === '0') {
        hide();
        message.success(`${text}成功`);
        return true;
      } else {
        hide()
      }
    } catch (error) {
      hide();
      message.error(`${text}失败请重试！`);
    }
  };
  // 禁用/启用  status 0激活，1禁用
  const handleStatus = async (selectedRows, status, text) => {
    const hide = message.loading(`正在${text}`);
    try {
      let res = await changeStatus({
        ids: selectedRows.map(row => row.id).toString(),
        status: status
      });
      if (res.code === '0') {

        hide();
        message.success(`${text}成功`);
        return true;
      } else {
        hide()
      }
    } catch (error) {
      hide();
      message.error(`${text}失败请重试！`);
    }
};

  const tableSelectChange = (selectedRowKeys, selectedRows) =>{
    handleSelectedRowKeys(selectedRowKeys)
    handleSelectedRows(selectedRows)
  }

  const rowSelection = {
    selectedRowKeys,
    onChange: tableSelectChange,
  };

  return (
    <>
      <ProTable
        className={`${styles.dataDicTable} rest-pro-table-form-compact`}
        options={{density: false,fullScreen:true, reload:false, setting:true}}
        headerTitle="数据字典列表"
        actionRef={actionRef}
        size='small'
        scroll={{y:height }}
        rowSelection={
          AuthComponent.getAuth('dataDic.index.on_off')
          ? rowSelection
          : false
        }
        pagination={{
          showSizeChanger: true,
          showTotal: (total, range) => `${range[0]}-${range[1]} 共 ${total} 项`
        }}
        rowKey="id"
        toolBarRender={(action, {selectedRows}) => [
          <AuthComponent authCode="dataDic.index.add">
            <Button  icon='plus' type="primary" onClick={() => {
              handleCreateModalVisible(true)}}>
                新建
            </Button>
          </AuthComponent>,
          <AuthComponent authCode="dataDic.index.on_off">
            <Button icon='check-circle' onClick={() => {
              if (selectedRows.length === 0) {
                message.error("请选择启用的条目")
              } else {
                confirm({
                  title: '提示',
                  content: '确认操作后，该数据将被启用，你还要继续吗？',
                  cancelText: '取消',
                  okText: '确认',
                  onOk: async () => {
                    const result = await handleStatus(selectedRows, '0', '启用');
                    if(result){
                      actionRef.current.reload();
                      handleSelectedRows([])
                      handleSelectedRowKeys([])
                    }
                  }
                })
              }
            }}>启用</Button>
            <Button icon='stop' style={{marginLeft: '10px'}} onClick={() => {
              if (selectedRows.length === 0) {
                message.error("请选择停用的条目")
              } else {
                confirm({
                  title: '提示',
                  content: '确认操作后，该数据将被停用无法使用，你还要继续吗？',
                  cancelText: '取消',
                  okText: '确认',
                  onOk: async () => {
                    const result = await handleStatus(selectedRows, '1', '停用');
                    if(result){
                      actionRef.current.reload();
                      handleSelectedRows([])
                      handleSelectedRowKeys([])
                    }
                  }
                })
              }
            }}>停用</Button>
          </AuthComponent>,
        ]}
        beforeSearchSubmit={beforeSearchSubmit}
        columns={columns}
        request={(params)=>{
          let data = {
            current: params.current,
            pageSize: params.pageSize,
            keySearch: keySearch
          }
        return getDataTable(data)
        }}
      >
      </ProTable>
        {/* 新建 */}
        <CreateForm
          onSubmit={async value => {
            const success = await handleSubmit(value, '添加');
            if (success) {
              handleCreateModalVisible(false);
              actionRef.current.reload();
            }
          }}
          onCancel={() => handleCreateModalVisible(false)}
          createModalVisible={createModalVisible}
        />
    </>
  );
};

export default Form.create()(DataDictionary);

